import router from './router'

import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import getPageTitle from './utils/get-page-title'
import { useUserInfoStore } from './stores/userInfo'

const whiteList = ['/login', '/404']

router.beforeEach(async (to, from, next) => {
  NProgress.start()
  document.title = getPageTitle(to.meta.title as string)

  const useInfoStore = useUserInfoStore()
  const token = useInfoStore.token
  if (token) {
    if (to.path === '/login') {
      next('/')
    } else {
      const flag = !!useInfoStore.userInfo.name
      if (flag) {
        next()
      } else {
        console.log('-')

        try {
          await useInfoStore.getInfo()
          next(to)
        } catch (error) {
          useInfoStore.reset()
          next('/login')
        }
      }
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})
